﻿using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

public class OpenSolidWorks
{
    public static void Main(string[] args)
    {
        Console.WriteLine("hello world!");
        OpenSolidWorks.Open();
    }


    public static void  Open()
    {
    

        Console.WriteLine("测试");
        ModelDoc2 swModel ;

        SldWorks Swapp = new SldWorks();

        try
        {
            //启动solidworks

            Swapp.Visible = true;
            //Swapp.UserControl = true;

            // 获取当前活动的文档
            swModel = (ModelDoc2)Swapp.ActiveDoc;


         //   ISldWorks swApp = Utility.ConnectToSolidWorks();

            //连接
            if (Swapp != null && Swapp.GetProcessID() != -1)
            {
                Console.WriteLine("已连接到SolidWorks应用程序");

                // 获取当前活动的文档
                swModel = (ModelDoc2)Swapp.ActiveDoc;



                if (swModel != null)
                {


                    if (swModel.GetType() == (int)swDocumentTypes_e.swDocPART)
                    {

                        //获取图纸名称，确定是否正确连接
                        string partName = swModel.GetTitle();
                        Console.WriteLine("当前活动的零件名称： " + partName);

                        PartDoc partDoc = null;
                        Feature feature = null;
                        Dimension dimension = null;
                        partDoc = (PartDoc)swModel;


                        // 检查文档类型是否为零件文档
                        if (swModel.GetType() == (int)swDocumentTypes_e.swDocPART)
                        {
                            partDoc = (PartDoc)swModel;

                            // 获取特征管理器
                            FeatureManager featureMgr = (FeatureManager)swModel.FeatureManager;

                            // 获取特征数量
                            //int featureCount = featureMgr.GetFeatureCount();

                            // 遍历所有特征
                            // 遍历所有特征
                        }
                        // 执行其他操作...
                    }


//====================================================================== 装配体 ======================================================================
                    else if (swModel.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY)
                    {
                        string assemblyName = swModel.GetTitle();
                        Console.WriteLine("当前活动的装配体名称： " + assemblyName);

                        //=============遍历装配体中的零件=============
                        AssemblyDoc swAssembly = (AssemblyDoc)swModel;

                        object[] components = (object[])swAssembly.GetComponents(true);

                        foreach (object componentObj in components)
                        {
                            Component2 swComponent = (Component2)componentObj;

                            // 获取零件的名称
                            string componentName = swComponent.Name2;

                            // 在这里可以对每个零件进行处理
                            // 输出零件的名称或执行其他操作
                            Console.WriteLine("Component Name: " + componentName);

                            if (componentName.Equals("JC35SA22-1-1")) {




                                //=================================================遍历配合==============================================================================
                                var swFeat = (Feature)swComponent.FirstFeature();
                                Feature swMateFeat = null;
                                Feature swSubFeat = default(Feature);
                                Mate2 swMate = default;
                                Component2 swComp = swComponent;
                                MateEntity2[] swMateEnt = new MateEntity2[3];
                                //string fileName = null;
                                //int errors = 0;
                                //int warnings = 0;
                                int i = 0;
                                double[] entityParameters = new double[8];

                                int a = 0;

                                //从特征树中查找配合文件夹 Iterate over features in FeatureManager design tree

                                while ((swFeat != null))
                                {

                  
                                    if ("MateGroup" == swFeat.GetTypeName())
                                    {
                                        //       Console.WriteLine("\"MateGroup\" == swFeat.GetTypeName()");
                                        swMateFeat = (Feature)swFeat;

                                        //打印是否有配合
                                        Console.WriteLine( "打印是否有配合"+swMateFeat);
                                        a++;
                                        break;
                                    }
                                    swFeat = (Feature)swFeat.GetNextFeature();
                                }




                                Console.WriteLine("================================");
                                Console.WriteLine(swMateFeat.Name);
                                Debug.Print("  " + swMateFeat.Name);
                                Debug.Print("");

                                //获取第一个子配合特征 Get first mate, which is a subfeature

                                //for (int b = 0, b <= a , b++) { 
                                //}

                                swSubFeat = (Feature)swMateFeat.GetFirstSubFeature();
                                while ((swSubFeat != null))
                                {
                                    //  Console.WriteLine("(swSubFeat != null)");
                                    swMate = (Mate2)swSubFeat.GetSpecificFeature2();
                                    if ((swMate != null))
                                    {

                                        for (i = 0; i <= 1; i++)
                                        {
                                            Console.WriteLine("(swSubFeat != null)");
                                            swMateEnt[i] = swMate.MateEntity(i);
                                            Debug.Print("    " + swSubFeat.Name);
                                            Debug.Print("      Type              = " + swMate.Type);
                                            Debug.Print("      Alignment         = " + swMate.Alignment);
                                            Debug.Print("      Can be flipped    = " + swMate.CanBeFlipped);
                                            Debug.Print("");
                                            swComp = (Component2)swMateEnt[i].ReferenceComponent;
                                            Debug.Print("      Component         = " + swComp.Name2);
                                            Debug.Print("      Mate enity type   = " + swMateEnt[i].ReferenceType);
                                            entityParameters = (double[])swMateEnt[i].EntityParams;
                                            Debug.Print("      (x,y,z)           = (" + (double)entityParameters[0] + ", " + (double)entityParameters[1] + ", " + (double)entityParameters[2] + ")");
                                            Debug.Print("      (i,j,k)           = (" + (double)entityParameters[3] + ", " + (double)entityParameters[4] + ", " + (double)entityParameters[5] + ")");
                                            Debug.Print("      Radius 1          = " + (double)entityParameters[6]);
                                            Debug.Print("      Radius 2          = " + (double)entityParameters[7]);
                                            Debug.Print("");



                                            if (swSubFeat.Name.Equals("距离5")) {

                                                if (swComp.Name2.Equals("JC35SA22-1-1/JC35SA-T369418_ASM_1_ASM_1_ASM-1/JC35SA-0732_1_1-1")) {
                                                    Debug.Print("=======================================");
                                                    swComp = (Component2)swMateEnt[i].ReferenceComponent;
                                                    Debug.Print("      Component         = " + swComp.Name2);
                                                    Debug.Print("      Mate enity type   = " + swMateEnt[i].ReferenceType);
                                                    entityParameters = (double[])swMateEnt[i].EntityParams;
                                                    Debug.Print("      (x,y,z)           = (" + (double)entityParameters[0] + ", " + (double)entityParameters[1] + ", " + (double)entityParameters[2] + ")");
                                                    Debug.Print("      (i,j,k)           = (" + (double)entityParameters[3] + ", " + (double)entityParameters[4] + ", " + (double)entityParameters[5] + ")");
                                                    Debug.Print("      Radius 1          = " + (double)entityParameters[6]);
                                                    Debug.Print("      Radius 2          = " + (double)entityParameters[7]);
                                                    Debug.Print("");


                                                    Debug.Print("=====================修改参数=====================");
                                                    Console.WriteLine();
                                                    Console.WriteLine("===========================test===========================");

                                                    var featureData = (DistanceMateFeatureData)swSubFeat.GetDefinition();
                                                    var distance = featureData.Distance;

                                                    Console.WriteLine("距离值当前为：" + distance + " mm");
                                                    Debug.Print("距离值当前为：" + distance +"mm");

                                                    // 修改距离值为新的值
                                                    featureData.Distance = 0.3;
                                                    // 更新配合特征
                                                    swSubFeat.ModifyDefinition(featureData, swModel, null);
                                                    // 重新生成
                                                    swModel.EditRebuild3();
                                                    // 打印修改后的距离值

                                                    Console.WriteLine("距离值已修改为：" + featureData.Distance + " mm");
                                                    Debug.Print("=====================修改参数=====================");
                                                    Console.WriteLine("===========================test===========================");

                                                }

                                                //var eqw =  swComp.GetMaterialPropertyValues2;
                                                //var yu =  eqw.GetObjectData;


                                                //var qwe = entityParameters.Length;
                                                //Console.WriteLine(" ");
                                                //Console.WriteLine("---------");
                                                //Console.WriteLine(yu);
                                                //Console.WriteLine(qwe);
                                                //Console.WriteLine("---------");
                                                //Console.WriteLine(" ");

                                                //Debug.Print("----------距离=5");
                                            }





                                        }
                                        Debug.Print(" ");
                                    }
                                    // 从配合组中遍历 下一个配合 Get the next mate in MateGroup
                                    swSubFeat = (Feature)swSubFeat.GetNextSubFeature();
                                }
                        }
                        


                            //--------------------------------------------------------------------------
                            //--------------------------------------------------------------------------
                            //--------------------------------------------------------------------------
                            //AssemblyDoc swAssembly = (AssemblyDoc)swModel;
                            //Mate2 swMate;
                            //    // 获取装配体中的所有配合
                            //    for (int i = 0; i < swAssembly.GetMateCount(); i++)
                            //    {
                            //        swMate = (Mate2)swAssembly.GetMate(i);

                            //        // 在这里可以对每个配合进行处理
                            //        // 获取配合的类型、参考实体、约束等信息
                            //        string mateType = swMate.Type.ToString();
                            //        string refEntity1 = swMate.ReferenceEntity(0).Name;
                            //        string refEntity2 = swMate.ReferenceEntity(1).Name;

                            //        // 输出配合信息
                            //        Console.WriteLine("Mate Type: " + mateType);
                            //        Console.WriteLine("Reference Entity 1: " + refEntity1);
                            //        Console.WriteLine("Reference Entity 2: " + refEntity2);
                            //        Console.WriteLine("----------------------------------");
                            //    }
                            //}
                            //--------------------------------------------------------------------------
                            //--------------------------------------------------------------------------
                            //--------------------------------------------------------------------------
                            // 执行其他操作...
                        }
                    }
                    else if (swModel.GetType() == (int)swDocumentTypes_e.swDocDRAWING)
                    {
                        string drawingName = swModel.GetTitle();
                        Console.WriteLine("当前活动的图纸名称： " + drawingName);
                        Console.WriteLine("当前活动的图纸名称： " + drawingName);

                        // 执行其他操作...
                    }
                    else
                    {
                        Console.WriteLine("当前活动的文档不是零件、装配体或图纸");
                    }
                }
                else
                {
                    Console.WriteLine("没有打开的文档");
                }


            }
            else
            {
                Console.WriteLine("无法连接到SolidWorks应用程序");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        finally
        {
            //// 释放资源/关闭solidworks
            //if (Swapp != null)
            //{
            //    Swapp.ExitApp();
            //}
           
        }

    }

    /// <summary>
    /// 遍历装配体零件
    /// </summary>
    /// <param name="swComp"></param>
    /// <param name="nLevel"></param>
    public static void TraverseCompXform(Component2 swComp, long nLevel)
    {
        object[] vChild;
        Component2 swChildComp;
        string sPadStr = "";
        MathTransform swCompXform;
        //  object vXform;
        long i;

        for (i = 0; i < nLevel; i++)
        {
            sPadStr = sPadStr + "  ";
        }
        swCompXform = swComp.Transform2;
        if (swCompXform != null)
        {
            ModelDoc2 swModel;
            swModel = (ModelDoc2)swComp.GetModelDoc2();

            try
            {
                //子零件文件名
                //Debug.Print(sPadStr + swComp.Name2);

                if (swComp.GetSelectByIDString() == "")
                {
                    //选择id
                    //Debug.Print(swComp.GetSelectByIDString());
                }
                else
                {
                }
            }
            catch
            {
            }
            if (swModel != null)
            {
                Debug.Print("Loading:" + swComp.Name2);
                //获取零件的一些信息，如属性，名字路径。
                string tempPartNum = swModel.get_CustomInfo2(swComp.ReferencedConfiguration, "PartNum");
                string tempName2 = swComp.Name2;
                string tempName = swModel.GetPathName();
                string tempConfigName = swComp.ReferencedConfiguration;
                string tempComponentRef = swComp.ComponentReference;
            }
        }
        else
        {
            ModelDoc2 swModel;
            swModel = (ModelDoc2)swComp.GetModelDoc2();
        }

        vChild = (object[])swComp.GetChildren();
        for (i = 0; i <= (vChild.Length - 1); i++)
        {
            swChildComp = (Component2)vChild[i];
            TraverseCompXform(swChildComp, nLevel + 1);
        }
    }
}











//public static void Main(string[] args)
//{
//    SldWorks swApp = null;
//    ModelDoc2 swModel = null;

//    try
//    {
//        // 连接到SolidWorks
//        swApp = Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application")) as SldWorks;
//        swModel = swApp.ActiveDoc as ModelDoc2;

//        // 检查文档类型
//        swDocumentTypes_e docType = (swDocumentTypes_e)swModel.GetType();
//        if (docType == swDocumentTypes_e.swDocPART)
//        {
//            PartDoc swPart = swModel as PartDoc;

//            // 获取零件中的尺寸
//            Feature swFeature = swPart.FirstFeature();
//            while (swFeature != null)
//            {
//                if (swFeature.GetTypeName2() == "Dimension")
//                {
//                    Dimension swDimension = swFeature.GetSpecificFeature2() as Dimension;

//                    // 修改尺寸
//                    if (swDimension != null)
//                    {
//                        double newDimensionValue = 10.0; // 设置新的尺寸值
//                        swDimension.Parameter = newDimensionValue;
//                    }
//                }

//                swFeature = swFeature.GetNextFeature() as Feature;
//            }
//        }
//        else
//        {
//            Console.WriteLine("当前打开的文档不是零件文件。");
//        }
//        // 断开连接
//        swApp.ExitApp();
//    }
//    catch (Exception e)
//    {
//        Console.WriteLine("连接到SolidWorks失败：" + e.Message);
//    }
//    finally
//    {
//        // 断开连接
//        if (swApp != null)
//        {
//            swApp.ExitApp();
//        }
//    }
//}
